/* 
  generator生成器 
  * 避免异步编程中回调嵌套过深
  * 惰性执行，yield之后需要调用next()来继续执行
*/

// 生成器模拟发号器
function * createMaker () {
  let id = 1
  while (true) {
    yield id++
  }
}

const idMaker = createMaker()
console.log(idMaker.next().value)
console.log(idMaker.next().value)
console.log(idMaker.next().value)

// 实现生成器让for...of来遍历对象
const obj = {
  life: ['打游戏', '看书', '喝茶'],
  learn: ['js', 'css', 'html'],
  work: ['study']
}
obj[Symbol.iterator] = function * () {
  const keys = Object.keys(this)
  for (const item of keys) {
    yield [item, obj[item]]
  }
}

for (const [key, val] of obj) {
  console.log(key, val)
}
